from web_elements_tools import XMU_Reporter
import threading
import json5 as json
import time
from typing import Dict
import os

msg_dict:Dict[str,str] = {}

class LogFile():
    """管理日志文件,支持+=填充日志"""
    def __init__(self, filePath="log.txt") -> None:
        self.file_path = filePath
    def __iadd__(self, other:str):
        with open(self.file_path, "a", encoding="utf-8") as f:
            f.write(other)
        return self
    @property
    def content(self)->str:
        """获取全部日志内容"""
        with open(self.file_path, "r", encoding="utf-8") as f:
            content = f.read()
        return content

def main_runner(user:str, pswd:str, driver1, driver2):
    global msg_dict
    if driver1 is not None:
        reporter = XMU_Reporter("E_dict.json5", driver1)
        msg = reporter.main(user, pswd)
    elif driver2 is not None:
        reporter = XMU_Reporter("E_dict.json5", driver2)
        msg = reporter.main(user, pswd)
    else:
        msg = "webdriver not found, please check https://developer.microsoft.com/en-us/microsoft-edge/tools/webdriver/"
    msg_dict[user] = msg


def main():
    # 更新驱动
    import Downloader
    driverChanged = {"EDGE":[],
                     "EDGE BETA":[]}
    
    log = LogFile()
    log += f"{time.asctime(time.localtime(time.time()))}:\n"
    try:
        driverChanged = Downloader.main()
    except Exception as e:
        log += f"\tEdge drivers may failed to update\n\t\t{e}\n"
    Driver_dict = Downloader.getUseableDriverPath()
    Driver_Edge = Driver_dict["EDGE"][0] if Driver_dict["EDGE"] else None
    Driver_EdgeBeta = Driver_dict["EDGE BETA"][0] if Driver_dict["EDGE BETA"] else None

    if not os.path.exists("E_dict.json5"):
        log += f"\t'E_dict.json5' file not found!\n"
        log += f"\tTrying download:{Downloader.downloadEdict()}\n"
    
    try:
        with open("users.json", 'r') as js_file:
            js_config = json.load(js_file)
            users     = js_config["users"] 
            for user in users:
                if len(user) == 2:
                    user.append("0000")
            is_Mult_Thread  = js_config["thread"]
    except:
        with open("users.json", 'w') as js_file:
            username = input("User Name: ")
            password = input("Password : ")
            dorm = ""
            users = [[username, password, dorm]]
            js_config = {"users": users,
                        "thread": False}
            is_Mult_Thread  = js_config["thread"]
            js_string = json.dumps(js_config, sort_keys=True, indent=4, separators=(',', ': '))
            js_file.write(js_string)
    # 判断并行打卡还是单独各自打卡
    if is_Mult_Thread:
        threadPool:list[threading.Thread] = []
        for k, user in enumerate(users):
            username, password, dorm = user[0], user[1], user[2]
            print(f"{k} starting {username}")
            t = threading.Thread(target=
                lambda: main_runner(username, password, Driver_Edge, Driver_EdgeBeta))
            t.start()
            threadPool.append(t)
            time.sleep(1)
        for i in threadPool:
            i.join()
    else:
        for k, user in enumerate(users):
            username, password, dorm = user[0], user[1], user[2]
            print(f"{k} starting {username}")
            main_runner(username, password, Driver_Edge, Driver_EdgeBeta)


    # 汇报驱动更新情况
    for key in driverChanged:
        if driverChanged[key]:
            log += f"\t{key} Driver Updated to {driverChanged[key]}\n"
    # 汇报用户打卡情况
    for k, user in enumerate(msg_dict):
        log += f"\t[{k}]-{user}:\t{msg_dict[user]}\n"
    # 更新规则表尝试解决问题
    if msg_dict[user].endswith("Wrong"):
        log += f"\tTrying download new dict:\n"
        log += f"\t\t{Downloader.downloadEdict()}\n"
    Downloader.clearUnusedDriver()

if __name__ == "__main__":
    main()